import logging
from logging.handlers import TimedRotatingFileHandler
from util.os import os_tool

"""
封装log方法
"""
# 初始化logger对象
logger = logging.getLogger(__name__)
# 设置日志等级:info等级
logger.setLevel(level=logging.INFO)
root_path = os_tool.get_root_path() + 'logs/'
# 创建logs目录
os_tool.mkdir(root_path)

'''
# info日志处理器
    # filename：日志文件名
    # when：日志文件按什么维度切分。'S'-秒；'M'-分钟；'H'-小时；'D'-天；'W'-周
    #       这里需要注意，如果选择 D-天，那么这个不是严格意义上的'天'，而是从你
    #       项目启动开始，过了24小时，才会从新创建一个新的日志文件，
    #       如果项目重启，这个时间就会重置。所以这里选择'MIDNIGHT'-是指过了午夜
    #       12点，就会创建新的日志。
    # interval：是指等待多少个单位 when 的时间后，Logger会自动重建文件。
    # backupCount：是保留日志个数。默认的0是不会自动删除掉日志。
'''
handler = TimedRotatingFileHandler(root_path + 'info.log',when = 'd',interval = 1,backupCount=30,encoding='utf-8')
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s  - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)


handler2 = TimedRotatingFileHandler(root_path + 'error.log',when = 'd',interval = 1,backupCount=30,encoding='utf-8')
handler2.setLevel(logging.ERROR)
formatter2 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler2.setFormatter(formatter2)
logger.addHandler(handler2)

handler3 = TimedRotatingFileHandler(root_path + 'warring.log',when = 'd',interval = 1,backupCount=30,encoding='utf-8')
handler3.setLevel(logging.WARNING)
formatter3 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler3.setFormatter(formatter)
logger.addHandler(handler3)

handler4 = logging.StreamHandler()
handler4.setLevel(logging.DEBUG)
formatter4 = logging.Formatter()
handler4.setFormatter(formatter4)
logger.addHandler(handler4)


def info(msg):
    logger.info(msg)


def debug(msg):
    logger.debug(msg)


def warning(msg):
    logger.warning(msg)


def error(msg):
    logger.error(msg)


def critical(msg):
    logger.critical(msg)

